#include "DeviceNormal.h"
#include <thrust\count.h>
#include <thrust\device_ptr.h>


__device__ float compNormal(float3* a, float3* b){
	return acosf(a->x*b->x + a->y*b->y + a->z*b->z);
}

__global__ void detectLocalPlanarStructure(float3* data, bool* localPlanarStructure){
	int x = blockIdx.x * blockDim.x + threadIdx.x;
	int y = blockIdx.y * blockDim.y + threadIdx.y;

	int tx, ty;

	float3* basis = &data[x + y * 640];
	float3* ref;
	unsigned char count = 0;

	for(int i = -2; i <= 2; i++){
		for(int j = -2; j <= 2; j++){
			tx = x + j;
			ty = y + i;

			tx = tx < 0 ? 0 : tx;
			tx = tx >= 640 ? 640 - 2 : tx;

			ty = ty < 0 ? 0 : ty;
			ty = ty >= 480 ? 480 - 2 : ty;

			ref = &data[tx + ty * 640];
			if(compNormal(basis, ref) < 0.20f * 0.26179938f)
				count++;
		}
	}

	localPlanarStructure[x + y * 640] = count > 15;
}


void DeviceNormal::segmentNormalMap(){
	detectLocalPlanarStructure<<<dim3(20, 20), dim3(32, 24)>>>
		(data, localPlanarStructure);
}
